﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace CRM.Database.Model
{
    public class TrainingsCoursesCollection : AbstractCollection
    {
        /// <summary>
        /// Стaтическая коллекция 
        /// </summary>
        protected static List<TrainingsCourses> _list;

        /// <summary>
        /// Список объектов
        /// </summary>
        public List<TrainingsCourses> TrainingsCoursesList
        {
            get
            {
                return Entities.TrainingsCourses.ToList();
                if (_list == null)
                    _list = DB.Entities.TrainingsCourses.ToList();
                return _list;
            }
        }

        /// <summary>
        /// Обнуление статической коллекции
        /// </summary>
        protected override void SetStaticListToNULL()
        {
            _list = null;
        }

        /// <summary>
        /// Получение статического списка для хранения объектов
        /// </summary>
        /// <returns></returns>
        public override object GetStaticCollection()
        {
            return _list;
        }

        /// <summary>
        /// Получение элемента из коллекции по идентификатору
        /// </summary>
        /// <param name="itemId">Идентификатор</param>
        /// <returns>Элемент</returns>
        public override object GetItemById(int itemId)
        {
            return Entities.TrainingsCourses.Find(itemId);
        }

        #region Overrides of AbstractCollection

        /// <summary>
        /// Обновление элемента в коллекции
        /// </summary>
        /// <param name="item">Новый элемент</param>
        /// <param name="userLogin">Логин пользователя, который делает изменения</param>
        /// <returns>Результат операции</returns>
        public bool Update(object item, string userLogin)
        {
            var newObject = (TrainingsCourses) item;
            if (newObject == null)
                return false;

            var object4Update = GetItemByIdFromDatabase(newObject.GetKeyValue()) as TrainingsCourses;
            if (object4Update == null)
                return false;

            if (!string.IsNullOrEmpty(newObject.Name))
                object4Update.Name = newObject.Name;

            if (!string.IsNullOrEmpty(newObject.LinkToFeedBack))
                object4Update.LinkToFeedBack = newObject.LinkToFeedBack;

            if (!string.IsNullOrEmpty(newObject.LinkToMaterial))
                object4Update.LinkToMaterial = newObject.LinkToMaterial;

            if (!string.IsNullOrEmpty(newObject.LinkToProgramm))
                object4Update.LinkToProgramm = newObject.LinkToProgramm;

            if (!string.IsNullOrEmpty(newObject.Description))
                object4Update.Description = newObject.Description;

            object4Update.IdRubric = newObject.IdRubric;
            object4Update.Duration = newObject.Duration;
            object4Update.ParticipantCount = newObject.ParticipantCount;

            object4Update.IsActive = newObject.IsActive;
            return base.Update(object4Update, userLogin);
        }

        /// <summary>
        /// Получение списка элементов
        /// </summary>
        /// <returns>Список элементов</returns>
        public override List<object> GetList()
        {
            return new List<object>(TrainingsCoursesList);
        }

        /// <summary>
        /// Получение типа текущего элемента
        /// </summary>
        /// <returns></returns>
        protected override Type GetItemType()
        {
            return typeof (TrainingsCourses);
        }

        #endregion

        #region Extended properties

        /// <summary>
        /// список активных объектов
        /// </summary>
        public List<TrainingsCourses> TrainingsCoursesActiveList
        {
            get
            {
                var result = new List<TrainingsCourses>();
                if (TrainingsCoursesList.Count < 1) return result;
                result.AddRange(TrainingsCoursesList.Where(item => item.IsActive));
                return result;
            }
        }

        /// <summary>
        /// Возвращает список активных курсов с присутсвующими тренерами, площадками и аудиториями
        /// </summary>
        /// <returns></returns>
        public List<TrainingsCourses> FullDefinedCourses
        {
            get
            {
                var result = new List<TrainingsCourses>();
                foreach (TrainingsCourses course in TrainingsCoursesActiveList)
                {
                    if (course.TrainingsCoursesTrainers.Count > 0)
                        if (course.TrainingsCoursesPlaces.Count > 0)
                            if (course.TrainingsCoursesAuditoriums.Count > 0)
                                if (course.TrainingsCoursesAndTypes.Count > 0)
                                    result.Add(course);
                }
                return result;
            }
        }

        /// <summary>
        /// Возвращает список активных выездных курсов с присутсвующими тренерами, площадками и аудиториями
        /// </summary>
        /// <returns></returns>
        public List<TrainingsCourses> FullDefinedRemoteCourses
        {
            get
            {
                var result = new List<TrainingsCourses>();
                foreach (TrainingsCourses course in TrainingsCoursesActiveList)
                {
                    if (course.IsRemote)
                        if (course.TrainingsCoursesTrainers.Count > 0)
                            if (course.TrainingsCoursesPlaces.Count > 0)
                                if (course.TrainingsCoursesAuditoriums.Count > 0)
                                    if (course.TrainingsCoursesAndTypes.Count > 0)
                                        result.Add(course);
                }
                return result;
            }
        }

        /// <summary>
        /// Возвращает список курсов из расписания курсов в виде назначений для календаря
        /// </summary>
        /// <returns></returns>
        public List<SchedulerAppointments> CoursesAsSchedulerAppointments
        {
            get
            {
                var schedulesCol = new TrainingsSchedulesCollection();
                var result = new List<SchedulerAppointments>();
                foreach (TrainingsSchedules schedule in schedulesCol.TrainingsSchedulesList)
                {
                    var course = (TrainingsCourses) GetItemById(schedule.IdTrainingsCource);
                    if (schedule.TrainingCoursesStatuses == null) continue;
                    //не включать отмененные и черновые курсы
                    if (schedule.TrainingCoursesStatuses.IdTrainingCoursesStatus == 1 ||
                        schedule.TrainingCoursesStatuses.IdTrainingCoursesStatus == 6) continue;
                    if (course == null) continue;
                    var appointment = new SchedulerAppointments
                                          {
                                              Location = schedule.LocationName,
                                              ResourceID = schedule.IdTrainingsTrainer,
                                              StartDate = schedule.PlannedDate.Date,
                                              //EndDate = schedule.PlannedDate.AddDays(course.Duration),
                                              EndDate = schedule.PlannedDate.Date.AddDays(course.DurationForScheduler),
                                              Subject = course.Name,
                                              Status = 0,
                                              Type = 0,
                                              Label = 1,
                                              AllDay = false,
                                              UniqueID = schedule.IdTrainingsSchedule
                                          };
                    result.Add(appointment);
                }
                return result;
            }
        }

        #endregion

        #region Extended methods

        /// <summary>
        /// Возвращает список активных курсов заданного типа с присутсвующими тренерами, площадками и аудиториями 
        /// </summary>
        /// <returns></returns>
        public List<TrainingsCourses> GetFullDefinedCoursesByCourseType(int idCourseType)
        {
            if (!(idCourseType > 0))
                return FullDefinedCourses;
            var result = new List<TrainingsCourses>();
            foreach (TrainingsCourses course in TrainingsCoursesActiveList)
            {
                if (course.TrainingsCoursesAuditoriums.Count > 0)
                    if (course.TrainingsCoursesPlaces.Count > 0)
                        if (course.TrainingsCoursesTrainers.Count > 0)
                            if (course.TrainingsCoursesAndTypes.Count > 0)
                            {
                                foreach (TrainingsCoursesAndTypes type in course.TrainingsCoursesAndTypes)
                                {
                                    if (type.IdTraningCoursesType == idCourseType)
                                        result.Add(course);
                                }
                            }
            }
            return result;
        }

        /// <summary>
        /// Удаление курса вместе с привязками к другим объектам
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public new bool Delete(object item)
        {
            var course = (TrainingsCourses) item;
            if (course == null) return false;
            //удаление привязок курса к тренерам
            var trainersCol = new TrainingsTrainersCollection();
            List<TrainingsTrainers> trainersList = trainersCol.GetTrainersListByCourse(course);
            if (trainersList != null)
            {
                foreach (TrainingsTrainers trainer in trainersList)
                {
                    if (trainer != null)
                        course.DeleteTrainer(trainer);
                }
            }
            //удаление привязок курса к площадкам
            var placesCol = new TrainingsPlacesCollection();
            List<TrainingsPlaces> placesList = placesCol.GetPlacesListByCourse(course);
            if (placesList != null)
            {
                foreach (TrainingsPlaces place in placesList)
                {
                    if (place != null)
                        course.DeletePlace(place);
                }
            }
            //удаление привязок курса к целевым аудиториям
            var auditoriumsCol = new TrainingsAuditoriumsCollection();
            List<TrainingsAuditoriums> auditoriumsList = auditoriumsCol.GetAuditoriumsListByCourse(course);
            if (auditoriumsList != null)
            {
                foreach (TrainingsAuditoriums auditorium in auditoriumsList)
                {
                    if (auditorium != null)
                        course.DeleteAuditorium(auditorium);
                }
            }
            //удаление привязок курса к типам курсов
            var typesCol = new TrainingCoursesTypesCollection();
            List<TrainingCoursesTypes> coursesTypesList =
                typesCol.GetTrainingsCoursesTypesByCourseId(course.IdTrainingsCourse);
            if (coursesTypesList != null)
            {
                foreach (TrainingCoursesTypes type in coursesTypesList)
                {
                    if (type != null)
                        course.DeleteType(type);
                }
            }
            //удаление самого курса
            return base.Delete(item);
        }

        #endregion
    }
}